package com.shundr.user;

import java.util.Timer;
import java.util.TimerTask;

import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

import com.shundr.R;
import com.shundr.base.BaseActivity;
import com.shundr.common.util.ProgressDialogHelper;
import com.shundr.common.util.ToastHelper;
import com.shundr.frame.constant.LContext;
import com.shundr.frame.http.LHttpRequest;
import com.shundr.frame.service.SmsObserver;
import com.shundr.frame.util.StringUtil;
import com.shundr.user.http.UserRequest;
import com.shundr.user.model.UserInfo;
import com.shundr.user.util.UserUtil;

public class ChangePhoneActivity extends BaseActivity implements
		OnClickListener {
	private View vVerifyOldPassword;
	private View vSetNewPassword;
	private EditText etPassword;
	private Button btnClearPassword;
	private Button btnNextStep;

	private EditText etUserName;
	private EditText etCode;
	private Button btnClearUserName;
	private Button btnGetCaptcha;
	private Button btnChangePhone;
	
	private String userPhone="";
	
	private Timer mTimer;
	private static final int TOTAL = 60;
	private int timerTotal = TOTAL;

	private Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			try {
				switch (msg.what) {
				case UserRequest.GET_CONFIRM_USERINFO_SUCCESSED:
//					ToastHelper.toastShort(mContext, msg.obj.toString());
					vVerifyOldPassword.setVisibility(View.GONE);
					vSetNewPassword.setVisibility(View.VISIBLE);
					break;
				case UserRequest.UPDATE_USERPHONE_SUCCESSED:
					UserUtil.saveUserPhone(mContext, userPhone);
					ToastHelper.toastShort(mContext, msg.obj.toString());
					finish();
					break;
				case UserRequest.CHECK_PHONE_SUCCESSED:
					new UserRequest(mContext, mHandler).getAuthCode(etUserName.getText().toString(), UserInfo.CatpchaType.RESET_PHONE);
					mHandler.sendEmptyMessage(1999);
					break;
				case UserRequest.CHECK_CAPTCHA_SUCCESSED:
					new UserRequest(mContext, mHandler).updateUserPhone(userPhone);
					break;
				case 1999:
					mTimer = new Timer();
					mTimer.schedule(new TimerTask() {
						
						@Override
						public void run() {
							mHandler.sendEmptyMessage(2000);
						}
					}, 0,1000);
					break;
				case 2000:
					if(timerTotal != 0){
						timerTotal = timerTotal - 1;
						btnGetCaptcha.setText(timerTotal + "秒后重新获取");
						btnGetCaptcha.setBackgroundResource(R.drawable.btn_gray_light_selector);
						btnGetCaptcha.setEnabled(false);
					}else{
						timerTotal = TOTAL;
						btnGetCaptcha.setText("点击重新获取");
						btnGetCaptcha.setBackgroundResource(R.drawable.btn_orange_light_selector);
						btnGetCaptcha.setEnabled(true);
						mTimer.cancel();
						mTimer = null;
					}
					break;
				case LHttpRequest.REQUEST_FAILED:
					ToastHelper.toastShort(mContext, msg.obj.toString());
					break;
				default:
					break;
				}
				ProgressDialogHelper.dismiss();
			} catch (Exception e) {
				e.printStackTrace();
			}
			super.handleMessage(msg);
		}

	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_change_phone);
		vVerifyOldPassword = (View) findViewById(R.id.layout_verify_password);
		vSetNewPassword = (View) findViewById(R.id.layout_set_new_phone);
		etPassword = (EditText) findViewById(R.id.et_password);
		btnClearPassword = (Button) findViewById(R.id.btn_password_clear);
		btnNextStep = (Button) findViewById(R.id.btn_next_step11);

		btnClearPassword.setOnClickListener(this);
		btnNextStep.setOnClickListener(this);

		etUserName = (EditText) findViewById(R.id.et_username);
		etCode = (EditText) findViewById(R.id.et_code);
		btnClearUserName = (Button) findViewById(R.id.btn_name_clear);
		btnGetCaptcha = (Button) findViewById(R.id.btn_get_auth_code);
		btnChangePhone = (Button) findViewById(R.id.btn_change_phone);

		btnClearUserName.setOnClickListener(this);
		btnGetCaptcha.setOnClickListener(this);
		btnChangePhone.setOnClickListener(this);
		textChange();
		initSmsObserver();
	}

	private SmsObserver mSmsObserver;
	private void initSmsObserver(){
		mSmsObserver = new SmsObserver(this, new Handler(), etCode);
		// 注册短信变化监听
		getContentResolver().registerContentObserver(Uri.parse("content://sms/"), true, mSmsObserver);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_password_clear:
			etPassword.setText("");
			break;
		case R.id.btn_next_step11:
			checkPassword();
			break;
		case R.id.btn_name_clear:
			etUserName.setText("");
			break;
		case R.id.btn_get_auth_code:
			userPhone=etUserName.getText().toString().trim();
			if(StringUtil.isMobileNO(userPhone)){
				new UserRequest(mContext, mHandler).checkPhone(userPhone);
			}else{
				ToastHelper.toastShort(mContext, "手机号码格式不正确");
			}
			break;
		case R.id.btn_change_phone:
			checkCaptcha();
			break;
		default:
			break;
		}
	}
	private void checkPassword() {

		if (StringUtil.isNull(etPassword.getText().toString())) {
//			ToastHelper.toastShort(mContext, "请输入6到16位非空格密码");
			ToastHelper.toastShort(mContext, "请输入密码");
			etPassword.setText("");
			return;
		}
//		if (etPassword.getText().toString().length() < 6) {
//			ToastHelper.toastShort(mContext, "输入的密码长度太短,请重新输入");
//			return;
//		}
//		if (etPassword.getText().toString().length() > 16) {
//			ToastHelper.toastShort(mContext, "输入的密码长度太长,请重新输入");
//			return;
//		}
		ProgressDialogHelper.show(mContext, "正在验证密码...");
		new UserRequest(mContext, mHandler).getConfirmUserInfo(etPassword.getText().toString().trim());
	}
	
	private void checkCaptcha(){
		try {
			userPhone=etUserName.getText().toString().trim();
			if(StringUtil.isNull(userPhone)){
				ToastHelper.toastShort(mContext, "请输入手机号码");
				return;
			}
			if(!StringUtil.isMobileNO(userPhone)){
				ToastHelper.toastShort(mContext, "请输入正确格式的手机号码");
				return;
			}
			UserInfo info = LContext.userInfo;
			if(StringUtil.isEqual(userPhone, info.getUserPhone())){
				ToastHelper.toastShort(mContext, "请输入和当前用户不同的手机号码");
				return;
			}
			String code=etCode.getText().toString().trim();
			if(StringUtil.isNull(code)){
				ToastHelper.toastShort(mContext, "请输入验证码");
				return;
			}
			if((code).length()<6||(code).length()>6){
				ToastHelper.toastShort(mContext, "请输入正确的验证码");
				return;
			}
			if(StringUtil.isNull(etCode.getText().toString().trim())){
				ToastHelper.toastShort(mContext, "请输入验证码");
				return;
			}
			ProgressDialogHelper.show(mContext, "检查验证码...");
			new UserRequest(mContext, mHandler).checkCaptcha(userPhone, code);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	private void textChange(){
		etUserName.addTextChangedListener(new TextWatcher() {
			
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				
			}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				
			}
			
			@Override
			public void afterTextChanged(Editable s) {
				if(s.length() > 0){
					btnClearUserName.setVisibility(View.VISIBLE);
				}else{
					btnClearUserName.setVisibility(View.GONE);
				}
				if(s.length() == 11){
					if(StringUtil.isMobileNO(s.toString())){
						btnGetCaptcha.setBackgroundResource(R.drawable.btn_orange_light_selector);
						btnGetCaptcha.setEnabled(true);
					}else{
						ToastHelper.toastShort(mContext, "请输入正确的手机号");
						btnGetCaptcha.setBackgroundResource(R.drawable.btn_gray_light_selector);
						btnGetCaptcha.setEnabled(false);
					}
				}else{
					btnGetCaptcha.setBackgroundResource(R.drawable.btn_gray_light_selector);
					btnGetCaptcha.setEnabled(false);
				}
				if(s.length()>=12){
					ToastHelper.toastShort(mContext, "请输入正确的手机号");
				}
			}
		});
		
		etPassword.addTextChangedListener(new TextWatcher() {
			
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				
			}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				
			}
			
			@Override
			public void afterTextChanged(Editable s) {
				if(s.length() > 0){
					btnClearPassword.setVisibility(View.VISIBLE);
				}else{
					btnClearPassword.setVisibility(View.GONE);
				}
			}
		});
		
	}
	
	@Override
	protected void onDestroy() {
		if (mTimer != null) {
			mTimer.cancel();
			mTimer = null;
		}
		getContentResolver().unregisterContentObserver(mSmsObserver);
		super.onDestroy();
	}

}
